from app.libs.httpUtils import HTTP
from flask import current_app


class YuShuBook:
    """
    鱼书Api
    """
    isbn_url = 'http://t.yushu.im/v2/book/isbn/{}'
    keyword_url = 'http://t.yushu.im/v2/book/search?q={}&count={}&start={}'

    def __init__(self):
        self.total = 0
        self.books = []

    def search_by_isbn(self, isbn):
        data = HTTP.get(self.isbn_url.format(isbn))
        self.__fill_isbn_data(data)

    def search_by_keyword(self, keyword, page):
        data = HTTP.get(self.keyword_url.format(keyword, current_app.config['PER_COUNT'], self.calculate_start(page)))
        self.__fill_keyword_data(data)

    def calculate_start(self, page):
        return (page - 1) * current_app.config['PER_COUNT']

    def __fill_isbn_data(self, data):
        if data:
            self.total = 1
            self.books.append(data)

    def __fill_keyword_data(self, data):
        if data:
            self.total = data['total']
            self.books = data['books']
